import os
from django import VERSION as DJANGO_VERSION
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

class CompressorSettings(object):
    # Main switch
    COMPRESS_ENABLED = getattr(settings,'COMPRESS_ENABLED',not settings.DEBUG)
    # Allows changing verbosity from the settings.
    COMPRESS_VERBOSE = getattr(settings,'COMPRESS_VERBOSE',False)
    # GET variable that disables compressor e.g. "nocompress"
    COMPRESS_DEBUG_TOGGLE = getattr(settings,'COMPRESS_DEBUG_TOGGLE','None')
    # the backend to use when parsing the JavaScript or Stylesheet files
    COMPRESS_PARSER = getattr(settings,'COMPRESS_PARSER','compressor.parser.AutoSelectParser')
    COMPRESS_OUTPUT_DIR = getattr(settings,'COMPRESS_OUTPUT_DIR','CACHE')
    COMPRESS_STORAGE = getattr(settings,'COMPRESS_STORAGE','compressor.storage.CompressorFileStorage')

    COMPRESS_CSS_COMPRESSOR = getattr(settings,'COMPRESS_CSS_COMPRESSOR','compressor.css.CssCompressor')
    COMPRESS_JS_COMPRESSOR = getattr(settings,'COMPRESS_JS_COMPRESSOR','compressor.js.JsCompressor')

    COMPRESS_URL = getattr(settings,'COMPRESS_URL',None)
    COMPRESS_ROOT = getattr(settings,'COMPRESS_ROOT',None)

    COMPRESS_CSS_FILTERS = getattr(settings,'COMPRESS_CSS_FILTERS',['compressor.filters.css_default.CssAbsoluteFilter'])
    COMPRESS_CSS_HASHING_METHOD = getattr(settings,'COMPRESS_CSS_HASHING_METHOD','mtime')

    COMPRESS_JS_FILTERS = getattr(settings,'COMPRESS_JS_FILTERS',['compressor.filters.jsmin.JSMinFilter'])
    COMPRESS_PRECOMPILERS = getattr(settings,'COMPRESS_PRECOMPILERS',(
        # ('text/coffeescript', 'coffee --compile --stdio'),
        # ('text/less', 'lessc {infile} {outfile}'),
        # ('text/x-sass', 'sass {infile} {outfile}'),
        # ('text/x-scss', 'sass --scss {infile} {outfile}'),
    ))
    COMPRESS_CLOSURE_COMPILER_BINARY = getattr(settings,'COMPRESS_CLOSURE_COMPILER_BINARY','java -jar compiler.jar')
    COMPRESS_CLOSURE_COMPILER_ARGUMENTS = getattr(settings,'COMPRESS_CLOSURE_COMPILER_ARGUMENTS','')
    COMPRESS_CSSTIDY_BINARY = getattr(settings,'COMPRESS_CSSTIDY_BINARY','csstidy')
    COMPRESS_CSSTIDY_ARGUMENTS = getattr(settings,'COMPRESS_CSSTIDY_ARGUMENTS','--template=highest')
    COMPRESS_YUI_BINARY = getattr(settings,'COMPRESS_YUI_BINARY','java -jar yuicompressor.jar')
    COMPRESS_YUI_CSS_ARGUMENTS = getattr(settings,'COMPRESS_YUI_CSS_ARGUMENTS','')
    COMPRESS_YUI_JS_ARGUMENTS = getattr(settings,'COMPRESS_YUI_JS_ARGUMENTS','')
    COMPRESS_DATA_URI_MAX_SIZE = getattr(settings,'COMPRESS_DATA_URI_MAX_SIZE',1024)

    # the cache backend to use
    COMPRESS_CACHE_BACKEND = getattr(settings,'COMPRESS_CACHE_BACKEND',None)
    # the dotted path to the function that creates the cache key
    COMPRESS_CACHE_KEY_FUNCTION = getattr(settings,'COMPRESS_CACHE_KEY_FUNCTION','compressor.cache.simple_cachekey')
    # rebuilds the cache every 30 days if nothing has changed.
    COMPRESS_REBUILD_TIMEOUT = getattr(settings,'COMPRESS_REBUILD_TIMEOUT',60 * 60 * 24 * 30)  # 30 days
    # the upper bound on how long any compression should take to be generated
    # (used against dog piling, should be a lot smaller than REBUILD_TIMEOUT
    COMPRESS_MINT_DELAY = getattr(settings,'COMPRESS_MINT_DELAY',30)  # seconds
    # check for file changes only after a delay
    COMPRESS_MTIME_DELAY = getattr(settings,'COMPRESS_MTIME_DELAY',10)  # seconds
    # enables the offline cache -- also filled by the compress command
    COMPRESS_OFFLINE = getattr(settings,'COMPRESS_OFFLINE',False)
    # invalidates the offline cache after one year
    COMPRESS_OFFLINE_TIMEOUT = getattr(settings,'COMPRESS_OFFLINE_TIMEOUT',60 * 60 * 24 * 365)  # 1 year
    # The context to be used when compressing the files "offline"
    COMPRESS_OFFLINE_CONTEXT = getattr(settings,'COMPRESS_OFFLINE_CONTEXT',{})
    # The name of the manifest file (e.g. filename.ext)
    COMPRESS_OFFLINE_MANIFEST = getattr(settings,'COMPRESS_OFFLINE_MANIFEST','manifest.json')
    
if CompressorSettings.COMPRESS_ROOT is None:
    CompressorSettings.COMPRESS_ROOT = getattr(settings, 'STATIC_ROOT', None)
    if not CompressorSettings.COMPRESS_ROOT:
        CompressorSettings.COMPRESS_ROOT = settings.MEDIA_ROOT
if not CompressorSettings.COMPRESS_ROOT:
    raise ImproperlyConfigured("COMPRESS_ROOT setting must be set")
CompressorSettings.COMPRESS_ROOT = os.path.normcase(os.path.abspath(CompressorSettings.COMPRESS_ROOT))

# Uses Django 1.3's STATIC_URL by default or falls back to MEDIA_URL
if CompressorSettings.COMPRESS_URL is None:
    CompressorSettings.COMPRESS_URL = getattr(settings, 'STATIC_URL', None)
    if not CompressorSettings.COMPRESS_URL:
        CompressorSettings.COMPRESS_URL = settings.MEDIA_URL
if not CompressorSettings.COMPRESS_URL.endswith('/'):
    raise ImproperlyConfigured("URL settings (e.g. COMPRESS_URL) "
                               "must have a trailing slash")

if CompressorSettings.COMPRESS_CACHE_BACKEND is None:
    # If we are on Django 1.3 AND using the new CACHES setting...
    if DJANGO_VERSION[:2] >= (1, 3) and hasattr(settings, 'CACHES'):
        CompressorSettings.COMPRESS_CACHE_BACKEND = 'default'
    else:
        # falling back to the old CACHE_BACKEND setting
        CompressorSettings.COMPRESS_CACHE_BACKEND = getattr(settings, 'CACHE_BACKEND', None)
        if not CompressorSettings.COMPRESS_CACHE_BACKEND:
            raise ImproperlyConfigured("Please specify a cache backend in your settings.")

if not CompressorSettings.COMPRESS_OFFLINE_CONTEXT:
    CompressorSettings.COMPRESS_OFFLINE_CONTEXT = {'MEDIA_URL': settings.MEDIA_URL}
    # Adds the 1.3 STATIC_URL setting to the context if available
    if getattr(settings, 'STATIC_URL', None):
        CompressorSettings.COMPRESS_OFFLINE_CONTEXT['STATIC_URL'] = settings.STATIC_URL

if not isinstance(CompressorSettings.COMPRESS_PRECOMPILERS, (list, tuple)):
    raise ImproperlyConfigured("The COMPRESS_PRECOMPILERS setting "
                               "must be a list or tuple. Check for "
                               "missing commas.")
for key,value in CompressorSettings.__dict__.items():
    if key.startswith('COMPRESS'):
        setattr(settings,key,value)